<?php

namespace app\api\model;

class Product extends Base
{
    protected $hidden=['delete_time','create_time','summary','update_time','pivot'];
    /**
     * 获取器
     * @param $value
     * @param $data
     * @return string
     */
    public function getMainImgUrlAttr($value,$data){
        return $this->imgUrl($value,$data);
    }

    //定义和商品表的一对多关系
    public function withProperty(){
        return $this->hasMany('ProductProperty','product_id','id');
    }
    //定义和商品图片表的一对多关系
    public function withProductImage(){
        return $this->hasMany('ProductImage','product_id','id');
    }

    /**
     *发现最近新品
     */
    public static function findNew($count){
        $data=self::limit($count)
            ->order('create_time desc')
            ->select();
        return $data;
    }
    /**
     *获取某个分类下的商品
     */
    public static function ProductInCategory($id){
        $res=self::where('category_id','=',$id)->select();
        return $res;
    }

    public static function getProductInfo($id){
        // return $data=self::with(['withProperty','withProductImage.withImage'])->find($id);
        /**
         * 为了连表查询,按照order的字段排序图片,是用如下的查询(闭包的威力)
         */
        $data=self::with([
            'withProductImage'=>function($query){
                $query->with(['withImage'])
                    ->order('order','asc');
            }
            ])
            ->with(['withProperty'])
            ->find($id);
        return $data;
    }
}
